/*
=== 动态API管理控制器 - 已废弃 ===

此文件已被注释，因为已迁移到新的动态API管理系统

替代方案：
- 新的管理端点：/api/DynamicApiManagement/*
- 自动生成的端点：/api/dynamic/*
- 迁移指南：docs/API_MIGRATION_GUIDE.md

原始代码保留在注释中，如需回滚可以取消注释

using AuthService.Application.Services;
using AuthService.Domain.Entities;
using AuthService.Api.Models;
using AuthService.Api.Extensions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using HttpMethod = AuthService.Domain.Enums.HttpMethod;

namespace AuthService.Api.Controllers;

/// <summary>
/// 动态API管理控制器
/// 提供动态API端点的CRUD操作
/// </summary>
[ApiController]
[Route("api/v{version:apiVersion}/[controller]")]
[ApiVersion("1.0")]
[Authorize(Policy = "AdminOnly")]
public class DynamicApiController : ControllerBase
{
    private readonly IDynamicApiService _dynamicApiService;
    private readonly ILogger<DynamicApiController> _logger;

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="dynamicApiService">动态API服务</param>
    /// <param name="logger">日志记录器</param>
    public DynamicApiController(IDynamicApiService dynamicApiService, ILogger<DynamicApiController> logger)
    {
        _dynamicApiService = dynamicApiService;
        _logger = logger;
    }

    /// <summary>
    /// 获取所有启用的API端点
    /// </summary>
    /// <param name="tenantId">租户ID（可选），用于多租户环境下的数据隔离</param>
    /// <returns>返回启用的API端点列表，包含端点的基本信息和配置</returns>
    /// <response code="200">成功获取API端点列表</response>
    /// <response code="500">服务器内部错误</response>
    /// <example>
    /// GET /api/dynamicapi?tenantId=tenant1
    /// </example>
    [HttpGet]
    [ProducesResponseType(typeof(IEnumerable<object>), 200)]
    [ProducesResponseType(500)]
    public async Task<IActionResult> GetEnabledEndpoints([FromQuery] string? tenantId = null)
    {
        try
        {
            var endpoints = await _dynamicApiService.GetEnabledEndpointsAsync(tenantId);
            var response = endpoints.Select(MapToResponse).ToList();
            return Ok(response);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取API端点列表失败");
            return StatusCode(500, new { error = ex.Message });
        }
    }

    /// <summary>
    /// 创建新的API端点
    /// </summary>
    /// <param name="request">创建API端点的请求对象，包含端点的所有配置信息</param>
    /// <returns>返回创建成功的API端点信息</returns>
    /// <response code="201">API端点创建成功</response>
    /// <response code="400">请求参数无效</response>
    /// <response code="409">API端点已存在（路径和方法组合重复）</response>
    /// <response code="500">服务器内部错误</response>
    /// <example>
    /// POST /api/dynamicapi
    /// {
    ///   "name": "用户查询API",
    ///   "method": "GET",
    ///   "pathTemplate": "/api/users/{id}",
    ///   "targetUrl": "http://user-service/users/{id}",
    ///   "requireAuthentication": true
    /// }
    /// </example>
    [HttpPost]
    [ProducesResponseType(typeof(object), 201)]
    [ProducesResponseType(400)]
    [ProducesResponseType(409)]
    [ProducesResponseType(500)]
    public async Task<IActionResult> CreateEndpoint([FromBody] CreateEndpointRequest request)
    {
        try
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var endpoint = new DynamicApiEndpoint
            {
                Name = request.Name,
                Description = request.Description,
                Method = HttpMethodExtensions.FromString(request.Method.ToString()),
                PathTemplate = request.PathTemplate,
                TargetUrl = request.TargetUrl ?? string.Empty,
                IsEnabled = request.IsEnabled,
                RequireAuthentication = request.RequireAuthentication,
                RequiredRoles = request.RequiredRoles ?? [],
                RequiredPermissions = request.RequiredPermissions ?? [],
                RateLimitPerMinute = request.RateLimitPerMinute,
                TimeoutSeconds = request.TimeoutSeconds ?? 30,
                RetryCount = request.RetryCount ?? 0,
                CacheSeconds = request.CacheSeconds ?? 0,
                Headers = request.Headers ?? [],
                QueryParameters = request.QueryParameters ?? [],
                RequestTransformation = request.RequestTransformation,
                ResponseTransformation = request.ResponseTransformation,
                Version = request.Version ?? "1.0",
                Tags = request.Tags ?? [],
                TenantId = request.TenantId,
                Priority = request.Priority,
                Metadata = request.Metadata,
                CreatedBy = User.Identity?.Name
            };

            var createdEndpoint = await _dynamicApiService.CreateEndpointAsync(endpoint);

            return CreatedAtAction(nameof(GetEndpoint), new { id = createdEndpoint.Id }, new
            {
                createdEndpoint.Id,
                createdEndpoint.Name,
                createdEndpoint.Description,
                Method = createdEndpoint.Method.ToStringValue(),
                createdEndpoint.PathTemplate,
                createdEndpoint.TargetService,
                createdEndpoint.TargetUrl,
                createdEndpoint.IsEnabled,
                createdEndpoint.RequireAuthentication,
                createdEndpoint.RequiredRoles,
                createdEndpoint.RequiredPermissions,
                createdEndpoint.Priority,
                createdEndpoint.Tags,
                createdEndpoint.Version,
                createdEndpoint.CreatedAt,
                createdEndpoint.UpdatedAt
            });
        }
        catch (ArgumentException ex)
        {
            return BadRequest(new { error = ex.Message });
        }
        catch (InvalidOperationException ex)
        {
            return Conflict(new { error = ex.Message });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "创建API端点失败");
            return StatusCode(500, new { error = ex.Message });
        }
    }

    /// <summary>
    /// 获取指定的API端点
    /// </summary>
    /// <param name="id">端点ID</param>
    /// <returns>API端点详情</returns>
    [HttpGet("{id:guid}")]
    public async Task<IActionResult> GetEndpoint(Guid id)
    {
        try
        {
            var endpoint = await _dynamicApiService.GetByIdAsync(id);
            if (endpoint == null)
            {
                return NotFound(new { error = "API端点不存在" });
            }

            var response = MapToResponse(endpoint);
            return Ok(response);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取API端点失败，ID: {EndpointId}", id);
            return StatusCode(500, new { error = ex.Message });
        }
    }

    /// <summary>
    /// 更新API端点
    /// </summary>
    /// <param name="id">端点ID</param>
    /// <param name="request">更新请求</param>
    /// <returns>更新的API端点</returns>
    [HttpPut("{id:guid}")]
    public async Task<IActionResult> UpdateEndpoint(Guid id, [FromBody] UpdateEndpointRequest request)
    {
        try
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            // 获取现有端点
            var existingEndpoint = await _dynamicApiService.GetByIdAsync(id);
            if (existingEndpoint == null)
            {
                return NotFound(new { error = "API端点不存在" });
            }

            // 更新端点属性
            if (!string.IsNullOrEmpty(request.Name))
                existingEndpoint.Name = request.Name;
            if (request.Description != null)
                existingEndpoint.Description = request.Description;
            if (request.Method.HasValue)
                existingEndpoint.Method = HttpMethodExtensions.FromString(request.Method.Value.ToString());
            if (!string.IsNullOrEmpty(request.PathTemplate))
                existingEndpoint.PathTemplate = request.PathTemplate;
            if (!string.IsNullOrEmpty(request.TargetUrl))
                existingEndpoint.TargetUrl = request.TargetUrl;
            if (request.IsEnabled.HasValue)
                existingEndpoint.IsEnabled = request.IsEnabled.Value;
            if (request.RequireAuthentication.HasValue)
                existingEndpoint.RequireAuthentication = request.RequireAuthentication.Value;
            if (request.RequiredRoles != null)
                existingEndpoint.RequiredRoles = request.RequiredRoles;
            if (request.RequiredPermissions != null)
                existingEndpoint.RequiredPermissions = request.RequiredPermissions;
            if (request.RateLimitPerMinute.HasValue)
                existingEndpoint.RateLimitPerMinute = request.RateLimitPerMinute;
            if (request.TimeoutSeconds.HasValue)
                existingEndpoint.TimeoutSeconds = request.TimeoutSeconds.Value;
            if (request.RetryCount.HasValue)
                existingEndpoint.RetryCount = request.RetryCount.Value;
            if (request.CacheSeconds.HasValue)
                existingEndpoint.CacheSeconds = request.CacheSeconds.Value;
            if (request.Headers != null)
                existingEndpoint.Headers = request.Headers;
            if (request.QueryParameters != null)
                existingEndpoint.QueryParameters = request.QueryParameters;
            if (request.RequestTransformation != null)
                existingEndpoint.RequestTransformation = request.RequestTransformation;
            if (request.ResponseTransformation != null)
                existingEndpoint.ResponseTransformation = request.ResponseTransformation;
            if (!string.IsNullOrEmpty(request.Version))
                existingEndpoint.Version = request.Version;
            if (request.Tags != null)
                existingEndpoint.Tags = request.Tags;
            if (request.TenantId != null)
                existingEndpoint.TenantId = request.TenantId;
            if (request.Priority.HasValue)
                existingEndpoint.Priority = request.Priority.Value;
            if (request.Metadata != null)
                existingEndpoint.Metadata = request.Metadata;

            existingEndpoint.UpdatedBy = User.Identity?.Name;

            var updatedEndpoint = await _dynamicApiService.UpdateEndpointAsync(existingEndpoint);
            var response = MapToResponse(updatedEndpoint);
            return Ok(response);
        }
        catch (ArgumentException ex)
        {
            return BadRequest(new { error = ex.Message });
        }
        catch (InvalidOperationException ex)
        {
            return Conflict(new { error = ex.Message });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "更新API端点失败，ID: {EndpointId}", id);
            return StatusCode(500, new { error = ex.Message });
        }
    }

    /// <summary>
    /// 删除API端点
    /// </summary>
    /// <param name="id">端点ID</param>
    /// <returns>删除结果</returns>
    [HttpDelete("{id:guid}")]
    public async Task<IActionResult> DeleteEndpoint(Guid id)
    {
        try
        {
            var success = await _dynamicApiService.DeleteEndpointAsync(id, User.Identity?.Name);

            if (success)
            {
                return NoContent();
            }
            else
            {
                return NotFound(new { error = "API端点不存在" });
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "删除API端点失败，ID: {EndpointId}", id);
            return StatusCode(500, new { error = ex.Message });
        }
    }

    /// <summary>
    /// 启用API端点
    /// </summary>
    /// <param name="id">端点ID</param>
    /// <returns>操作结果</returns>
    [HttpPost("{id:guid}/enable")]
    public async Task<IActionResult> EnableEndpoint(Guid id)
    {
        try
        {
            var success = await _dynamicApiService.EnableEndpointAsync(id, User.Identity?.Name);

            if (success)
            {
                return Ok(new { message = "API端点已启用" });
            }
            else
            {
                return NotFound(new { error = "API端点不存在" });
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "启用API端点失败，ID: {EndpointId}", id);
            return StatusCode(500, new { error = ex.Message });
        }
    }

    /// <summary>
    /// 禁用API端点
    /// </summary>
    /// <param name="id">端点ID</param>
    /// <returns>操作结果</returns>
    [HttpPost("{id:guid}/disable")]
    public async Task<IActionResult> DisableEndpoint(Guid id)
    {
        try
        {
            var success = await _dynamicApiService.DisableEndpointAsync(id, User.Identity?.Name);

            if (success)
            {
                return Ok(new { message = "API端点已禁用" });
            }
            else
            {
                return NotFound(new { error = "API端点不存在" });
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "禁用API端点失败，ID: {EndpointId}", id);
            return StatusCode(500, new { error = ex.Message });
        }
    }

    /// <summary>
    /// 验证API端点配置
    /// </summary>
    /// <param name="request">验证请求</param>
    /// <returns>验证结果</returns>
    [HttpPost("validate")]
    public IActionResult ValidateEndpoint([FromBody] CreateEndpointRequest request)
    {
        try
        {
            var endpoint = new DynamicApiEndpoint
            {
                Name = request.Name,
                Description = request.Description,
                Method = HttpMethodExtensions.FromString(request.Method.ToString()),
                PathTemplate = request.PathTemplate,
                TargetUrl = request.TargetUrl ?? string.Empty,
                TimeoutSeconds = request.TimeoutSeconds ?? 30,
                RetryCount = request.RetryCount ?? 0
            };

            var validationResult = _dynamicApiService.ValidateEndpoint(endpoint);

            return Ok(new
            {
                isValid = validationResult.IsValid,
                errors = validationResult.Errors
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "验证API端点配置失败");
            return StatusCode(500, new { error = ex.Message });
        }
    }

    /// <summary>
    /// 将实体映射为响应DTO
    /// </summary>
    private static EndpointResponse MapToResponse(DynamicApiEndpoint endpoint)
    {
        return new EndpointResponse
        {
            Id = endpoint.Id,
            Name = endpoint.Name,
            Description = endpoint.Description,
            Method = endpoint.Method.ToStringValue(),
            PathTemplate = endpoint.PathTemplate,
            TargetUrl = endpoint.TargetUrl ?? string.Empty,
            IsEnabled = endpoint.IsEnabled,
            RequireAuthentication = endpoint.RequireAuthentication,
            RequiredRoles = endpoint.RequiredRoles ?? [],
            RequiredPermissions = endpoint.RequiredPermissions ?? [],
            RateLimitPerMinute = endpoint.RateLimitPerMinute,
            TimeoutSeconds = endpoint.TimeoutSeconds,
            RetryCount = endpoint.RetryCount,
            CacheSeconds = endpoint.CacheSeconds,
            Version = endpoint.Version ?? "1.0",
            Tags = endpoint.Tags ?? [],
            TenantId = endpoint.TenantId,
            Priority = endpoint.Priority,
            CreatedAt = endpoint.CreatedAt,
            UpdatedAt = endpoint.UpdatedAt
        };
    }
}

*/
